package mbms.mobilebudget.bankaccount;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mbms.mobilebudget.R;
import mbms.mobilebudget.database.DatabaseHandler;
import mbms.mobilebudget.entity.BankAccount;
import mbms.mobilebudget.entity.EnumValues.AccountType;
import mbms.mobilebudget.entity.EnumValues.BankNameEnum;
import mbms.mobilebudget.entity.EnumValues.CurrencyType;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;

@SuppressLint("ShowToast")
public class BankAccountsAddUpdateActivity extends  OrmLiteBaseActivity<DatabaseHandler>  {

	private BankAccount acquiredBankAccount;
	private Spinner accountTypeSpinner;
	private Spinner currencyTypeSpinner;
	private Spinner bankNameSpinner;
	private EditText branch;
	private EditText accountNumber;
	private EditText IBAN;
	private boolean isAdd= true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bank_accounts_add_update);
		Intent intent = getIntent();
		
		acquiredBankAccount = (BankAccount) intent.getSerializableExtra("bankAccount");
		if(acquiredBankAccount==null){
			Toast.makeText(getApplicationContext(), 
					"Bank account not acquired", Toast.LENGTH_SHORT).show();
			return ;
		}
		
		if(acquiredBankAccount.getUser()!=null){

			//setContentView(android.R.layout.sp);
			accountTypeSpinner = (Spinner)findViewById(R.id.b_accountspinner);
			currencyTypeSpinner = (Spinner) findViewById(R.id.b_currencyspinner);
			bankNameSpinner = (Spinner) findViewById(R.id.b_banknamespinner);
			branch = (EditText) findViewById(R.id.b_branchinput);
			accountNumber = (EditText) findViewById(R.id.b_accountnumberinput);
			IBAN = (EditText) findViewById(R.id.b_ibaninput);
			accountTypeSpinner.setAdapter(new ArrayAdapter<AccountType>(this, android.R.layout.simple_spinner_item,
					AccountType.values()));
			currencyTypeSpinner.setAdapter(new ArrayAdapter<CurrencyType>(this, android.R.layout.simple_spinner_item,
					CurrencyType.values()));
			bankNameSpinner.setAdapter(new ArrayAdapter<BankNameEnum>(this, android.R.layout.simple_spinner_item,
					BankNameEnum.values()));
			Button addUpdateButton = (Button)findViewById(R.id.b_addupdatebutton);
			
			if(acquiredBankAccount.getId()==null){
				addUpdateButton.setText("Add");
			}
			else{
				addUpdateButton.setText("Update");
				setData();
				isAdd=false;
			}
			
		}
		else {
			Toast.makeText(getApplicationContext(), 
					"User not acquired", Toast.LENGTH_SHORT).show();
			return ;
		}
		
		
	}
	public void addUpdateButtonClicked(View view){
		addUpdateHandler(isAdd);
	}
	private void addUpdateHandler(boolean isAdd){
		if(isAdd){
			addOperation();
		}
		else{
			updateOperation();
		}
	}
	public void addOperation() {
		BankAccountManager bankAccountManager = new BankAccountManager(getHelper(), getApplicationContext());
		BankAccount addableBankAccount =retrieveData();
		if(constraintHandler(addableBankAccount)){
			if(bankAccountManager.addBankAccount(addableBankAccount, acquiredBankAccount.getUser())!=null){
				Log.i("Add", "succesful");
				Toast.makeText(getApplicationContext(), "Add successful", Toast.LENGTH_SHORT).show();
				super.onBackPressed();
			}
			else{
				Toast.makeText(getApplicationContext(), "Add failed", Toast.LENGTH_SHORT).show();
				Log.e("Add", "failed");
			}
		}
		
		
	}

	private BankAccount retrieveData(){
		String s_branch = branch.getText().toString();
		String s_accountnumber = accountNumber.getText().toString();
		String s_iban =IBAN.getText().toString();
		AccountType e_accounttype = (AccountType) accountTypeSpinner.getSelectedItem();
		CurrencyType e_currencytype = (CurrencyType) currencyTypeSpinner.getSelectedItem();
		BankNameEnum e_bankname = (BankNameEnum) bankNameSpinner.getSelectedItem();
		
		BankAccount account = new BankAccount(null, e_bankname, s_branch, s_accountnumber,
				s_iban, e_accounttype, e_currencytype, acquiredBankAccount.getUser());
		return account;

		
	}
	private void setData(){
		branch.setText(acquiredBankAccount.getBranch());
		accountNumber.setText(acquiredBankAccount.getAccountNumber());
		IBAN.setText(acquiredBankAccount.getIBAN());
		accountTypeSpinner.setSelection(acquiredBankAccount.getAccountType().ordinal());
		currencyTypeSpinner.setSelection(acquiredBankAccount.getCurrencyType().ordinal());
		bankNameSpinner.setSelection(acquiredBankAccount.getBankName().ordinal());
		
	}
	public void updateOperation() {
		BankAccountManager bankAccountManager = new BankAccountManager(getHelper(), getApplicationContext());
		BankAccount updatableBankAccount = retrieveData();		
		updatableBankAccount.setId(acquiredBankAccount.getId());
		if(constraintHandler(updatableBankAccount)){
			if(bankAccountManager.updateBankAccount(updatableBankAccount)!=null){
				Log.i("Update", "succesful");
				Toast.makeText(getApplicationContext(), "Update successful", Toast.LENGTH_SHORT).show();
				super.onBackPressed();
				// liste refresh
			}
			else{
				Toast.makeText(getApplicationContext(), "Update failed", Toast.LENGTH_SHORT).show();
				Log.e("Update", "failed");
			}
		}
		
		
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.bank_accounts_add_update, menu);
		return true;
	}
	private boolean constraintHandler(BankAccount account){
		return mandatoryCheck(account)&&branchCheck(account.getBranch()) && bankAccountNumberCheck(account.getAccountNumber()) &&
				ibanCheck(account.getIBAN());
	}
	private boolean mandatoryCheck(BankAccount account) {
		if(account.getAccountNumber()!=null && account.getIBAN()!=null && account.getAccountType()!=null
				&&	account.getCurrencyType() !=null){
			return true;
		}
		else{
			Toast.makeText(getApplicationContext(), 
					"Mandatory fields must be filled", Toast.LENGTH_LONG).show();	
			return false;
		}

	}
	private boolean branchCheck(String branch){
		if (branch.equals("")||branch.matches("[-a-zA-Z ]+")) {
			return true;
		}
		else{
			Toast.makeText(getApplicationContext(), 
					"Branch is not valid", Toast.LENGTH_LONG).show();	
			return false;
		}
	}
	private boolean bankAccountNumberCheck(String number){
		if (number.matches("[0-9]+") && number.length() > 3) {
			return true;
		}
		else{
			Toast.makeText(getApplicationContext(), 
					"Account number is not valid", Toast.LENGTH_LONG).show();	
			return false;
		}
	}
	private boolean ibanCheck(String iban){
		
		if(!isIbanValid(iban)){
			return false;
		}
		try {
			Dao<BankAccount, Integer> bankDao = getHelper().getBankAccountDao();
			List<BankAccount> un = bankDao.queryForEq("iban", iban);
			if(un==null || un.isEmpty()){
				return true;
			}
			else{
				if(!isAdd && un.get(0).getId().equals(acquiredBankAccount.getId())){
					return true;
				}
				Toast.makeText(getApplicationContext(), 
						"IBAN is not unique", Toast.LENGTH_LONG).show();	
				return false;
			}
		}catch(Exception e){
			Toast.makeText(getApplicationContext(), 
					"error while checking uniqueness", Toast.LENGTH_LONG).show();	
			Log.e("error","eror");
			return false;
		}
		
		
	}
	public boolean isIbanValid(String iban)
    {
         String regExpn =
             "[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}";
     CharSequence inputStr = iban;

     Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
     Matcher matcher = pattern.matcher(inputStr);

     if(matcher.matches()){
    	 return true;	
     }
        
     else{
    	 Toast.makeText(getApplicationContext(), 
					"IBAN is not valid", Toast.LENGTH_LONG).show();	
    	 return false;
     }
    }
}
